package main

import (
	"net/http"
	"github.com/gorilla/mux"
	"html/template"
	"github.com/go-redis/redis"
	"github.com/gorilla/sessions"
)


var templates *template.Template
var store  = sessions.NewCookieStore([] byte("t0p-s3cr3t"))
var client *redis.Client


func main() {
	client = redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	templates = template.Must(template.ParseGlob("templates/*.html"))

	// 路由初始化，使用参考：https://www.jianshu.com/p/8ade70e51210
	r := mux.NewRouter()

	// 路由注册
	r.HandleFunc("/", indexGetHandler).Methods("GET")
	r.HandleFunc("/", indexPostHandler).Methods("POST")
	r.HandleFunc("/login", loginGetHandler).Methods("GET")
	r.HandleFunc("/logout", loginPostHandler).Methods("POST")

	// file server
	fs := http.FileServer(http.Dir("./static/"))
	// 增加URL前缀
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

	http.Handle("/", r)
	http.ListenAndServe(":1313", nil)
}

func indexGetHandler(w http.ResponseWriter, r *http.Request){
	comments, err := client.LRange("comments", 0, 10).Result()
	if err != nil {
		return
	}
	templates.ExecuteTemplate(w, "index.html", comments)
}


func indexPostHandler(w http.ResponseWriter, r *http.Request){
	r.ParseForm()
	comment := r.PostForm.Get("comment")

	client.LPush("comments", comment)
	http.Redirect(w, r, "/", 302)
}

func loginGetHandler(w http.ResponseWriter, r *http.Request)  {
	templates.ExecuteTemplate(w, "login.html", nil)
}

func loginPostHandler(w http.ResponseWriter, r *http.Request)  {
	r.ParseForm()
	username, _ := store.Get(r, "username")
	session, _ := store.Get(r, "session")
	session.Values["username"] = username
	session.Save(r, w)
}
